package com.gaoqi.mq.router;

import com.gaoqi.mq.utils.RabbitMQ;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 该类用于模拟 rabbitmq 路由模式消费者
 */
@Slf4j
public class Consumer1 {


    @SneakyThrows
    public void routerGetMessage() {
        //获取连接对象
        Connection rabbitConnection = RabbitMQ.getRabbitConnection();
        //获取通道
        Channel channel = rabbitConnection.createChannel();

        //通道指定交换机名 及交换类型
        channel.exchangeDeclare("logs_router", "direct");

        //创建临时队列
        String queue = channel.queueDeclare().getQueue();

        //交换机绑定队列(当前队列只取route key 为error)
        channel.queueBind(queue, "logs_router", "info");

        //消费消息
        channel.basicConsume(queue, true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                log.info("消费者1消费:{}", new String(body));
            }
        });

    }

    public static void main(String[] args) {
        new Consumer1().routerGetMessage();
    }
}
